'use strict';

const Service = require('egg').Service;
const { Op } = require('sequelize');
const TravelNote = require('../model/travelNote');
const TravelNoteComment = require('../model/travelNoteComment');
const { TravelNoteLike, TravelNoteFavorite } = require('../model/travelNoteInteraction');
const User = require('../model/user');

class TravelNoteService extends Service {
  /**
   * 创建游记
   * @param {object} noteData - 游记数据
   */
  async createNote(noteData) {
    const {
      user_id,
      title,
      cover_image,
      city,
      start_date,
      end_date,
      content,
      gallery_images,
      tags,
      visibility,
      status
    } = noteData;

    try {
      // 验证必填字段
      if (!title || !content) {
        return {
          success: false,
          message: '标题和内容不能为空'
        };
      }

      // 自动生成简介（从内容中提取前200个字符）
      const description = content
        .replace(/<[^>]*>/g, '') // 移除HTML标签
        .substring(0, 200);

      // 确保数组字段正确序列化为 JSON 字符串
      const galleryImagesJson = Array.isArray(gallery_images)
        ? JSON.stringify(gallery_images)
        : (gallery_images || JSON.stringify([]));

      const tagsJson = Array.isArray(tags)
        ? JSON.stringify(tags)
        : (tags || JSON.stringify([]));

      const note = await TravelNote.create({
        user_id,
        title,
        cover_image: cover_image || '',
        city: city || '',
        start_date: start_date || null,
        end_date: end_date || null,
        content,
        description,
        gallery_images: galleryImagesJson,
        tags: tagsJson,
        visibility: visibility || 'public',
        status: status || (visibility === 'public' ? 'pending' : 'draft'),
        published_at: status === 'approved' ? new Date() : null
      });

      return {
        success: true,
        message: '游记创建成功',
        data: note
      };
    } catch (error) {
      console.error('创建游记失败:', error);
      console.error('错误详情:', error.message);
      return {
        success: false,
        message: `创建游记失败: ${error.message}`
      };
    }
  }

  /**
   * 更新游记
   * @param {number} noteId - 游记ID
   * @param {number} userId - 用户ID
   * @param {object} updateData - 更新数据
   */
  async updateNote(noteId, userId, updateData) {
    try {
      const note = await TravelNote.findByPk(noteId);

      if (!note) {
        return {
          success: false,
          message: '游记不存在'
        };
      }

      // 权限检查：只有作者可以编辑
      if (note.user_id !== userId) {
        return {
          success: false,
          message: '无权编辑此游记'
        };
      }

      // 如果更新了内容，重新生成简介
      if (updateData.content) {
        updateData.description = updateData.content
          .replace(/<[^>]*>/g, '')
          .substring(0, 200);
      }

      // 如果从草稿改为公开，设置为待审核
      if (updateData.visibility === 'public' && note.visibility === 'private') {
        updateData.status = 'pending';
      }

      await note.update(updateData);

      return {
        success: true,
        message: '游记更新成功',
        data: note
      };
    } catch (error) {
      console.error('更新游记失败:', error);
      return {
        success: false,
        message: '更新游记失败'
      };
    }
  }

  /**
   * 删除游记
   * @param {number} noteId - 游记ID
   * @param {number} userId - 用户ID
   */
  async deleteNote(noteId, userId) {
    try {
      const note = await TravelNote.findByPk(noteId);

      if (!note) {
        return {
          success: false,
          message: '游记不存在'
        };
      }

      // 权限检查
      if (note.user_id !== userId) {
        return {
          success: false,
          message: '无权删除此游记'
        };
      }

      await note.destroy();

      // 删除相关数据（评论、点赞、收藏）
      await TravelNoteComment.destroy({ where: { note_id: noteId } });
      await TravelNoteLike.destroy({ where: { note_id: noteId } });
      await TravelNoteFavorite.destroy({ where: { note_id: noteId } });

      return {
        success: true,
        message: '游记删除成功'
      };
    } catch (error) {
      console.error('删除游记失败:', error);
      return {
        success: false,
        message: '删除游记失败'
      };
    }
  }

  /**
   * 获取游记详情
   * @param {number} noteId - 游记ID
   * @param {number} userId - 当前用户ID（可选）
   */
  async getNoteDetail(noteId, userId) {
    try {
      const note = await TravelNote.findByPk(noteId);

      if (!note) {
        return {
          success: false,
          message: '游记不存在'
        };
      }

      // 权限检查：私密游记只有作者可见
      if (note.visibility === 'private' && note.user_id !== userId) {
        return {
          success: false,
          message: '无权查看此游记'
        };
      }

      // 增加浏览量
      await note.increment('view_count');

      // 获取作者信息
      const author = await User.findByPk(note.user_id, {
        attributes: ['id', 'username', 'nickname', 'avatar']
      });

      // 检查用户是否点赞和收藏
      let is_liked = false;
      let is_favorited = false;

      if (userId) {
        const like = await TravelNoteLike.findOne({
          where: { note_id: noteId, user_id: userId }
        });
        const favorite = await TravelNoteFavorite.findOne({
          where: { note_id: noteId, user_id: userId }
        });

        is_liked = !!like;
        is_favorited = !!favorite;
      }

      const noteData = note.toJSON();

      return {
        success: true,
        data: {
          ...noteData,
          author: author ? author.toJSON() : null,
          is_liked,
          is_favorited
        }
      };
    } catch (error) {
      console.error('获取游记详情失败:', error);
      return {
        success: false,
        message: '获取游记详情失败'
      };
    }
  }

  /**
   * 获取游记列表
   * @param {object} params - 查询参数
   */
  async getNoteList(params) {
    const {
      page = 1,
      pageSize = 10,
      user_id,
      city,
      keyword,
      status,
      visibility,
      is_featured,
      order_by = 'created_at',
      order = 'DESC'
    } = params;

    // 确保 page 和 pageSize 是数字
    const pageNum = parseInt(page) || 1;
    const pageSizeNum = parseInt(pageSize) || 10;

    try {
      const where = {};

      // 筛选条件
      if (user_id) {
        where.user_id = user_id;
      }

      if (city) {
        where.city = city;
      }

      if (keyword) {
        where[Op.or] = [
          { title: { [Op.like]: `%${keyword}%` } },
          { content: { [Op.like]: `%${keyword}%` } },
          { description: { [Op.like]: `%${keyword}%` } }
        ];
      }

      if (status) {
        where.status = status;
      }

      if (visibility) {
        where.visibility = visibility;
      }

      if (is_featured !== undefined) {
        where.is_featured = is_featured;
      }

      // 查询总数
      const total = await TravelNote.count({ where });

      // 查询列表
      const notes = await TravelNote.findAll({
        where,
        include: [
          {
            model: User,
            as: 'author',
            attributes: ['id', 'username', 'nickname', 'avatar']
          }
        ],
        order: [[order_by, order]],
        offset: (pageNum - 1) * pageSizeNum,
        limit: pageSizeNum
      });

      return {
        success: true,
        data: {
          list: notes,
          total,
          page: pageNum,
          pageSize: pageSizeNum,
          totalPages: Math.ceil(total / pageSizeNum)
        }
      };
    } catch (error) {
      console.error('获取游记列表失败:', error);
      return {
        success: false,
        message: '获取游记列表失败'
      };
    }
  }

  /**
   * 点赞游记
   * @param {number} noteId - 游记ID
   * @param {number} userId - 用户ID
   */
  async likeNote(noteId, userId) {
    try {
      const note = await TravelNote.findByPk(noteId);

      if (!note) {
        return {
          success: false,
          message: '游记不存在'
        };
      }

      // 检查是否已点赞
      const existingLike = await TravelNoteLike.findOne({
        where: { note_id: noteId, user_id: userId }
      });

      if (existingLike) {
        return {
          success: false,
          message: '已点赞过此游记'
        };
      }

      // 创建点赞记录
      await TravelNoteLike.create({
        note_id: noteId,
        user_id: userId
      });

      // 增加点赞数
      await note.increment('like_count');

      return {
        success: true,
        message: '点赞成功'
      };
    } catch (error) {
      console.error('点赞游记失败:', error);
      return {
        success: false,
        message: '点赞失败'
      };
    }
  }

  /**
   * 取消点赞游记
   * @param {number} noteId - 游记ID
   * @param {number} userId - 用户ID
   */
  async unlikeNote(noteId, userId) {
    try {
      const note = await TravelNote.findByPk(noteId);

      if (!note) {
        return {
          success: false,
          message: '游记不存在'
        };
      }

      // 删除点赞记录
      const result = await TravelNoteLike.destroy({
        where: { note_id: noteId, user_id: userId }
      });

      if (result === 0) {
        return {
          success: false,
          message: '未点赞过此游记'
        };
      }

      // 减少点赞数
      await note.decrement('like_count');

      return {
        success: true,
        message: '取消点赞成功'
      };
    } catch (error) {
      console.error('取消点赞失败:', error);
      return {
        success: false,
        message: '取消点赞失败'
      };
    }
  }

  /**
   * 收藏游记
   * @param {number} noteId - 游记ID
   * @param {number} userId - 用户ID
   */
  async favoriteNote(noteId, userId) {
    try {
      const note = await TravelNote.findByPk(noteId);

      if (!note) {
        return {
          success: false,
          message: '游记不存在'
        };
      }

      // 检查是否已收藏
      const existingFavorite = await TravelNoteFavorite.findOne({
        where: { note_id: noteId, user_id: userId }
      });

      if (existingFavorite) {
        return {
          success: false,
          message: '已收藏过此游记'
        };
      }

      // 创建收藏记录
      await TravelNoteFavorite.create({
        note_id: noteId,
        user_id: userId
      });

      // 增加收藏数
      await note.increment('favorite_count');

      return {
        success: true,
        message: '收藏成功'
      };
    } catch (error) {
      console.error('收藏游记失败:', error);
      return {
        success: false,
        message: '收藏失败'
      };
    }
  }

  /**
   * 取消收藏游记
   * @param {number} noteId - 游记ID
   * @param {number} userId - 用户ID
   */
  async unfavoriteNote(noteId, userId) {
    try {
      const note = await TravelNote.findByPk(noteId);

      if (!note) {
        return {
          success: false,
          message: '游记不存在'
        };
      }

      // 删除收藏记录
      const result = await TravelNoteFavorite.destroy({
        where: { note_id: noteId, user_id: userId }
      });

      if (result === 0) {
        return {
          success: false,
          message: '未收藏过此游记'
        };
      }

      // 减少收藏数
      await note.decrement('favorite_count');

      return {
        success: true,
        message: '取消收藏成功'
      };
    } catch (error) {
      console.error('取消收藏失败:', error);
      return {
        success: false,
        message: '取消收藏失败'
      };
    }
  }

  /**
   * 获取用户收藏的游记列表
   * @param {number} userId - 用户ID
   * @param {object} params - 查询参数
   */
  async getUserFavoriteNotes(userId, params) {
    const {
      page = 1,
      pageSize = 10,
      order_by = 'created_at',
      order = 'DESC'
    } = params;

    // 确保 page 和 pageSize 是数字
    const pageNum = parseInt(page) || 1;
    const pageSizeNum = parseInt(pageSize) || 10;

    try {
      // 查询用户收藏的游记总数
      const total = await TravelNoteFavorite.count({
        where: { user_id: userId }
      });

      // 查询用户收藏的游记列表
      const favorites = await TravelNoteFavorite.findAll({
        where: { user_id: userId },
        include: [
          {
            model: TravelNote,
            as: 'note',
            include: [
              {
                model: User,
                as: 'author',
                attributes: ['id', 'username', 'nickname', 'avatar']
              }
            ]
          }
        ],
        order: [[order_by, order]],
        offset: (pageNum - 1) * pageSizeNum,
        limit: pageSizeNum
      });

      // 提取游记数据
      const notes = favorites.map(fav => fav.note);

      return {
        success: true,
        data: {
          list: notes,
          total,
          page: pageNum,
          pageSize: pageSizeNum,
          totalPages: Math.ceil(total / pageSizeNum)
        }
      };
    } catch (error) {
      console.error('获取用户收藏游记列表失败:', error);
      return {
        success: false,
        message: '获取用户收藏游记列表失败'
      };
    }
  }

  /**
   * 获取用户点赞的游记列表
   * @param {number} userId - 用户ID
   * @param {object} params - 查询参数
   */
  async getUserLikeNotes(userId, params) {
    const {
      page = 1,
      pageSize = 10,
      order_by = 'created_at',
      order = 'DESC'
    } = params;

    // 确保 page 和 pageSize 是数字
    const pageNum = parseInt(page) || 1;
    const pageSizeNum = parseInt(pageSize) || 10;

    try {
      // 查询用户点赞的游记总数
      const total = await TravelNoteLike.count({
        where: { user_id: userId }
      });

      // 查询用户点赞的游记列表
      const likes = await TravelNoteLike.findAll({
        where: { user_id: userId },
        include: [
          {
            model: TravelNote,
            as: 'note',
            include: [
              {
                model: User,
                as: 'author',
                attributes: ['id', 'username', 'nickname', 'avatar']
              }
            ]
          }
        ],
        order: [[order_by, order]],
        offset: (pageNum - 1) * pageSizeNum,
        limit: pageSizeNum
      });

      // 提取游记数据
      const notes = likes.map(like => like.note);

      return {
        success: true,
        data: {
          list: notes,
          total,
          page: pageNum,
          pageSize: pageSizeNum,
          totalPages: Math.ceil(total / pageSizeNum)
        }
      };
    } catch (error) {
      console.error('获取用户点赞游记列表失败:', error);
      return {
        success: false,
        message: '获取用户点赞游记列表失败'
      };
    }
  }

  /**
   * 添加评论
   * @param {object} commentData - 评论数据
   */
  async addComment(commentData) {
    const { note_id, user_id, parent_id, content } = commentData;

    try {
      const note = await TravelNote.findByPk(note_id);

      if (!note) {
        return {
          success: false,
          message: '游记不存在'
        };
      }

      // 创建评论
      const comment = await TravelNoteComment.create({
        note_id,
        user_id,
        parent_id,
        content
      });

      // 增加评论数
      await note.increment('comment_count');

      // 获取评论用户信息
      const user = await User.findByPk(user_id, {
        attributes: ['id', 'username', 'nickname', 'avatar']
      });

      const commentData_result = comment.toJSON();

      return {
        success: true,
        message: '评论成功',
        data: {
          ...commentData_result,
          user: user ? user.toJSON() : null
        }
      };
    } catch (error) {
      console.error('添加评论失败:', error);
      return {
        success: false,
        message: '添加评论失败'
      };
    }
  }

  /**
   * 获取游记评论列表
   * @param {number} noteId - 游记ID
   * @param {object} params - 查询参数
   */
  async getCommentList(noteId, params) {
    const { page = 1, pageSize = 20 } = params;

    // 确保 page 和 pageSize 是数字
    const pageNum = parseInt(page) || 1;
    const pageSizeNum = parseInt(pageSize) || 20;

    try {
      const where = {
        note_id: noteId,
        status: 'normal',  // 修改为 'normal' 以匹配模型定义
        parent_id: null // 只查询顶级评论
      };

      const total = await TravelNoteComment.count({ where });

      const comments = await TravelNoteComment.findAll({
        where,
        include: [
          {
            model: User,
            as: 'user',
            attributes: ['id', 'username', 'nickname', 'avatar']
          }
        ],
        order: [['created_at', 'DESC']],
        offset: (pageNum - 1) * pageSizeNum,
        limit: pageSizeNum
      });

      // 获取每条评论的回复
      const commentsWithReplies = await Promise.all(
        comments.map(async comment => {
          const replies = await TravelNoteComment.findAll({
            where: {
              parent_id: comment.id,
              status: 'normal'  // 修改为 'normal'
            },
            include: [
              {
                model: User,
                as: 'user',
                attributes: ['id', 'username', 'nickname', 'avatar']
              }
            ],
            order: [['created_at', 'ASC']],
            limit: 5
          });

          return {
            ...comment.toJSON(),
            replies: replies.map(r => r.toJSON())
          };
        })
      );

      return {
        success: true,
        data: {
          list: commentsWithReplies,
          total,
          page: pageNum,
          pageSize: pageSizeNum,
          totalPages: Math.ceil(total / pageSizeNum)
        }
      };
    } catch (error) {
      console.error('获取评论列表失败:', error);
      return {
        success: false,
        message: '获取评论列表失败'
      };
    }
  }

  /**
   * 删除评论
   * @param {number} commentId - 评论ID
   * @param {number} userId - 用户ID
   */
  async deleteComment(commentId, userId) {
    try {
      const comment = await TravelNoteComment.findByPk(commentId);

      if (!comment) {
        return {
          success: false,
          message: '评论不存在'
        };
      }

      // 权限检查：只有作者可以删除
      if (comment.user_id !== userId) {
        return {
          success: false,
          message: '无权删除此评论'
        };
      }

      // 软删除
      await comment.update({ status: 'deleted' });

      // 减少游记的评论数
      const note = await TravelNote.findByPk(comment.note_id);
      if (note) {
        await note.decrement('comment_count');
      }

      return {
        success: true,
        message: '评论删除成功'
      };
    } catch (error) {
      console.error('删除评论失败:', error);
      return {
        success: false,
        message: '删除评论失败'
      };
    }
  }

  /**
   * 审核游记（管理员）
   * @param {number} noteId - 游记ID
   * @param {string} status - 审核状态
   * @param {string} reason - 拒绝原因（可选）
   */
  async auditNote(noteId, status, reason) {
    try {
      const note = await TravelNote.findByPk(noteId);

      if (!note) {
        return {
          success: false,
          message: '游记不存在'
        };
      }

      const updateData = { status };

      if (status === 'approved') {
        updateData.published_at = new Date();
      }

      await note.update(updateData);

      return {
        success: true,
        message: '审核完成',
        data: { status, reason }
      };
    } catch (error) {
      console.error('审核游记失败:', error);
      return {
        success: false,
        message: '审核失败'
      };
    }
  }

  /**
   * 增加游记浏览量
   * @param {number} noteId - 游记ID
   */
  async increaseViewCount(noteId) {
    try {
      const note = await TravelNote.findByPk(noteId);

      if (!note) {
        return {
          success: false,
          message: '游记不存在'
        };
      }

      // 浏览量+1
      await note.update({
        view_count: (note.view_count || 0) + 1
      });

      return {
        success: true,
        message: '浏览量已更新',
        data: {
          view_count: note.view_count + 1
        }
      };
    } catch (error) {
      this.ctx.logger.error('增加浏览量失败:', error);
      return {
        success: false,
        message: '增加浏览量失败'
      };
    }
  }

  /**
   * 管理员更新游记（绕过权限检查）
   * @param {number} noteId - 游记ID
   * @param {object} updateData - 更新数据
   */
  async adminUpdateNote(noteId, updateData) {
    try {
      const note = await TravelNote.findByPk(noteId);

      if (!note) {
        return {
          success: false,
          message: '游记不存在'
        };
      }

      // 管理员可以直接更新，不检查权限
      await note.update(updateData);

      return {
        success: true,
        message: '更新成功',
        data: note
      };
    } catch (error) {
      this.ctx.logger.error('管理员更新游记失败:', error);
      return {
        success: false,
        message: '更新失败'
      };
    }
  }

}

module.exports = TravelNoteService;

